package cate.game.role.farm.pk;

import cate.common.rpc.path.RpcCommonPath;
import cate.common.table.d.GDFight;
import cate.common.table.d.GDFunc;
import cate.game.play.part.FightSide;
import cate.game.role.Role;
import cate.game.role.farm.AbstractFarm;
import cate.game.role.farm.pk.cmd.PkCmd;
import cate.game.role.farm.pk.msg.PkDataResp;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;
import org.apache.commons.lang3.StringUtils;

@NoteClass( "切磋")
public class MyPkPO extends AbstractFarm {
    @NoteField("总共切磋次数")
    public int totalTimes;
    @NoteField("切磋获胜次数")
    public int winTimes;

    @Override
    public int getFuncId() {
        return GDFunc.PK;
    }

    @Override
    public void onAfterOpen() {

    }

    @Override
    public int getFightFuncId() {
        return GDFunc.PK;
    }

    public void recordResult(boolean win) {
        totalTimes ++;
        if (win) {
            winTimes ++;
        }
    }

    public EcResult challenge(String tarRoleId, int tarSrvId) {
        EcResult r = new EcResult();
        if (fighting) {
            return r.fail("当前战斗未结束");
        }
        FightSide sideB = null;
        if (tarSrvId == role.getGame().config.srvId) {
            if (StringUtils.isBlank(tarRoleId)) {
                return r.fail("挑战玩家不存在");
            }
            if (tarRoleId.equals(role.getUid())) {
                return r.fail("不能和自己切磋");
            }
            Role opponent = role.getGame().role.getRole(tarRoleId, true);
            if (opponent == null) {
                return r.fail("挑战玩家不存在");
            }
            EcResult<FightSide> r_side = role.getGame().fight.side.createFightSideByRole(GDFight.Team.B, opponent, GDFunc.ADVENTURE);
            if (!r_side.ok()) {
                return r.fail("挑战玩家阵容构建失败");
            }
            sideB = r_side.data;
        } else {
            PkCmd cmd = new PkCmd();
            cmd.srvId = tarSrvId;
            cmd.roleId = tarRoleId;
            cmd = role.getGame().rpcSend().requestResponseGame(RpcCommonPath.ROLE_PK_G2G, tarSrvId, cmd, PkCmd.class);
            if (cmd.data != null) {
                sideB = role.getGame().fight.side.createFightSideByPlaySide(GDFight.Team.B, cmd.data);
            }
        }
        if (sideB == null) {
            return r.fail("挑战玩家阵容构建失败");
        }
        PkFTC ftc = new PkFTC(role);
        ftc.funcId = getFightFuncId();
        ftc.setPositionApply(GDFunc.ADVENTURE);
        r = role.getGame().play.startByRole(role, ftc, sideB);
        if (!r.ok()) {
            return r;
        }
        this.fighting = true;
        return r.success();
    }

    public void noticeUpdate() {
        role.sendNow(new PkDataResp(this));
    }
}
